package com.cs.test.task;

import com.cs.test.common.Constant;
import com.cs.test.mq.util.MessageHelper;
import com.cs.test.pojo.MsgLog;
import com.cs.test.service.MsgLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class ResendMsg {

    @Autowired
    private MsgLogService msgLogService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 最大投递次数
     */
    private static final int MAX_TRY_COUNT = 3;

    /**
     * 每30s拉取投递失败的消息, 重新投递
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void reSendMsg(){
        log.info("开始执行定时任务(重新投递消息)");
        // 获取投递失败的消息列表
        List<MsgLog> msgLogs = msgLogService.selectTimeoutMsg();
        for (MsgLog msgLog : msgLogs) {
            String msgId = msgLog.getMsgId();
            if (msgLog.getTryCount() >= MAX_TRY_COUNT){
                msgLogService.updateStatus(msgId,Constant.MsgLogStatus.DELIVER_FAIL);
                log.info("超过最大重试次数,消息投递失败,msgId:{}",msgId);
            }else {
                // 投递次数 + 1
                msgLogService.updateTryCount(msgId, msgLog.getNextTryTime());
                // 重发到rabbit<MQ
                CorrelationData correlationData = new CorrelationData(msgId);
                rabbitTemplate.convertAndSend(msgLog.getExchange(),msgLog.getRoutingKey(),
                        MessageHelper.objToMsg(msgLog),correlationData);

                log.info("第 " + (msgLog.getTryCount() + 1) + " 次重新投递消息");

            }
        }
        log.info("定时任务执行结束(重新投递消息)");
    }
}
